package com.kaigejava.listener.confirmlistener;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

/**
 * Created by kaigejava on 2019/7/21.
 * 消息确认的生产者
 */
public class Procuder4ConfirmListener {
    public static void main(String[] args) throws  Exception {
        //1:创建工厂对象
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setPort(5672);
        connectionFactory.setHost("192.168.31.130");
        connectionFactory.setVirtualHost("/");
        //2：通过工厂对象获取到连接对象
        Connection connection = connectionFactory.newConnection();
        //3:从连接对象中获取到消息通过channel对象
        Channel channel = connection.createChannel();
        //4:开启确认模式
        channel.confirmSelect();
        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm.save";
        //5:发送消息
        String message = "this message from confirm";
        for (int i = 0;i<5;i++){
            channel.basicPublish(exchangeName,routingKey,null,(message+i).getBytes());
        }
        //监听confirm响应
        channel.addConfirmListener(new ConfirmListener() {
            /**
             * 投递失成功响应
             * @param deliveryTag       消息唯一标签
             * @param multiple          是否批量
             * @throws IOException
             */
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("----投递成功确认响应---");
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {

                System.out.println("----投递失败确认响应---");
            }
        });

    }
}
